<?php
declare (strict_types = 1);

namespace app\service\logic\common\user;

use app\exception\LogicException;
use app\facade\OpenFacade;
use app\model\communal\UserWechatOpenModel;
use app\service\logic\BaseService;
use think\Model;

final class UserWechatOpenService extends BaseService
{
    protected string $modelClassName = 'UserWechatOpenModel';

    /**
     * @param $userId
     * @return int[]
     */
    public function isBindByUserId($userId)
    {
        $isBind = 1; // 已绑定
        $model = UserWechatOpenModel::findOrEmpty($userId);
        if ($model->isEmpty()) {
            $isBind = 2;
        }

        return [
            'is_bind' => $isBind
        ];
    }

    /**
     * 绑起来
     *
     * @param $userId
     * @param $params
     * @return UserWechatOpenModel|Model
     * @throws LogicException
     */
    public function bindByUserIdCode($userId, $params)
    {
        $model = UserWechatOpenModel::findOrEmpty($userId);
        if (!$model->isEmpty()) {
            throw new LogicException('已绑定微信');
        }

        $session = OpenFacade::code2Session($params['code']);
        $wechatUserinfo = OpenFacade::userinfo($session['openid']);
        return UserWechatOpenModel::create([
            'user_id' => $userId,
            'openid' => $wechatUserinfo['openid'],
            'nickname' => $wechatUserinfo['nickname'],
            'sex' => $wechatUserinfo['sex'],
            'province' => $wechatUserinfo['province'],
            'city' => $wechatUserinfo['city'],
            'country' => $wechatUserinfo['country'],
            'headimgurl' => $wechatUserinfo['headimgurl'],
            'privilege' => $wechatUserinfo['privilege'],
            'unionid' => $wechatUserinfo['unionid'],
        ]);
    }
}
